package com.fengye.security.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fengye.security.demo.mapper.MyUserMapper;
import com.fengye.security.demo.model.MyUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author sky
 * @Email <mailto:fengyexjtu@126.com>
 * @Date 2020/12/26 20:03
 * @Description
 **/
@Service("userDetailsService")
@Slf4j
public class MyUserDetailsService implements UserDetailsService {

  @Autowired private PasswordEncoder passwordEncoder;

  @Autowired private MyUserMapper myUserMapper;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    QueryWrapper<MyUser> wrapper = new QueryWrapper<>();
    wrapper.eq("username", username);
    MyUser myUser = myUserMapper.selectOne(wrapper);
    String roles = myUser.getRoles();
    String auth = myUser.getAuthorities();
    String all = roles.toUpperCase() + "," + auth.toLowerCase();
    List<GrantedAuthority> authorities =
        AuthorityUtils.commaSeparatedStringToAuthorityList(all);
    User user =
        new User(myUser.getUsername(), passwordEncoder.encode(myUser.getPassword()), authorities);
    log.info("user = {}", user);
    return user;
  }
}
